<template>
  <div>
    <el-tag
      v-for="tag in tags"
      :key="tag.name"
      :closable="tag.name !== '工作台'"
      :class="{active:tag.active}"
      :type="tag.type"
      @click="jumpFn(tag)"
      @close="closeFn(tag)"
    >
      {{ tag.name }}
    </el-tag>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tags: JSON.parse(localStorage.getItem('Tags')) || [{
        name: '工作台',
        path: '/dashboard',
        active: true
      }]
    }
  },
  watch: {
    $route(val) {
      // console.log(val)
      const include = this.tags.findIndex(item => {
        item.active = true
        return item.name === val.meta.title
      })
      // console.log(include)
      if (include === -1) {
        this.tags.push({
          name: val.meta.title,
          path: val.path,
          active: false
        })
      } else {
        this.tags.forEach(item => { item.active = true })
        this.tags[include].active = false
      }
      localStorage.setItem('Tags', JSON.stringify([{
        name: '工作台',
        path: '/dashboard',
        active: true
      }, {
        name: val.meta.title,
        path: val.path,
        active: false
      }]))
    }
  },
  methods: {
    jumpFn(val) {
      if (!val.active) return
      val.active = false
      this.$router.push({
        path: val.path
      })
    },
    closeFn(val) {
      console.log(this.tags.at(-1))
      this.tags.forEach((item, index) => {
        if (item.name === val.name) {
          this.tags.splice(index, 1)
          if (item.active === false) {
            this.jumpFn(this.tags.at(-1))
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.active{
  color: #000;
}
.el-tag.el-tag--light{
  margin: 10px;
}
</style>
